package com.syg.filter;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * Gateway中的三个核心概念：路由、断言(Predicate)、过滤器。
 *      路由：由唯一id、目的url、断言和过滤组成
 *      断言：即路由规则，用来判断哪些请求符合规则，符合的请求进行转发
 *      过滤器：分为GatewayFilter和GlobalFilter，前者作用于单一路由，后者作用于所有路由。过滤器可以对请求或者返回进行处理，如增加请求头、删除请求头
 *      在执行顺序上，GatewayFilter先执行，GlobalFilter后执行
 *
 * WebFilter与GatewayFilter和GlobalFilter的区别？
 */

@Component
public class RewritePathWebFilter implements WebFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest req = exchange.getRequest();
        String path = req.getURI().getRawPath();
        System.out.println("替换之前==" + path);
        // if (!path.contains("//")) {
        //     return chain.filter(exchange);
        // }

        // import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
        addOriginalRequestUrl(exchange, req.getURI());
        String newPath = path + "/12";
        System.out.println("替换之后==" + newPath);
        ServerHttpRequest request = req.mutate().path(newPath).build();
        // import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
        exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
        return chain.filter(exchange.mutate().request(request).build());
    }
}
